/* ************************************************************************************************

	Copyright (c) 2005-2006, IGR
	All Rights Reserved.
	Licensed under the Apache License version 2.0 or above.
	For more information on licensing, see:
        http://www.apache.org/licenses/


 ************************************************************************************************
 Objet Input Field
 VERSION:0.85
 DATE:16/03/2006
 ************************************************************************************************
Init parameter :
 Name:               Code name
 top:           	 Top position (in pixel)
 left:               Left position (in pixel)             
 width:              Width 
 datatype			 type of input (A=Alpha-N=Num-D=Date-H=hour-P=password-Hi=hidden-T=textArea)
 parent              object parent
 objPar              object of parameter
 		autoUp		Automatic UpperCase Conversion if true
 		isRequired	Field is surrounded in red whith a star if true
 		disable		True if the area is disabled
 		nbChar		Max number of characters you can type
 		rows		Max number of lines if datatype=textarea
 		initValue	Value of the field on load

*************************************************************************************************/


// *************************************
// CONSTRUCTOR
// *************************************


rialto.widget.Text=function(name,top,left,width,datatype,parent,objPar){
    	//base object parameter
	    var objParam=new Object;
	    objParam.name=name;
	    objParam.type="text";
	    objParam.left=left;
	    objParam.top=top;
  	    objParam.width=width;
  	    
	    if (objPar != null){objParam.position=objPar.position;}
		//base constructor
	    this.base = rialto.widget.AbstractComponent;    
	    this.base(objParam);
         
        //type of input      
        if(rialto.lang.isStringIn(datatype,['T','P','A','N','I','D','H','Hi'])){
            this.datatype = datatype;        
        }
        else{
            this.datatype = 'A';        
        }                        
        if(this.datatype=='P'){
            this.inputType= "password";
        }
        else{
            if(this.datatype=="Hi"){
                this.inputType= "hidden";
            }
            else{this.inputType= "text";}
        }
        //Default value
        this.autoUp=false;
        this.isRequired=false;
        this.disable=false;
        this.nbchar=50;
		this.rows = 5;
		this.initValue=null;
		this.wvalue="";
		this.accessKey="";
		this.tabIndex=rialto.widget.Form.prototype.tabIndex++;
        //set the value with the properties of the objPar object
        if (objPar){                           
	        if (rialto.lang.isNumber(objPar.nbchar)){
	            this.nbchar = objPar.nbchar;        
	        } 
	        if (rialto.lang.isBoolean(objPar.autoUp)){
	            this.autoUp = objPar.autoUp;        
	        }
			if (rialto.lang.isBoolean(objPar.disable)){
	            this.disable = objPar.disable;        
	        } 
	        if (rialto.lang.isBoolean(objPar.isRequired)){
	            this.isRequired = objPar.isRequired;        
	        }  	       
	        if (rialto.lang.isNumber(objPar.rows)){
	            this.rows = objPar.rows;        
	        }  
			if (rialto.lang.isString(objPar.initValue)){
	            this.initValue = objPar.initValue;        
	        } 
	        if (rialto.lang.isString(objPar.accessKey,true)){
	            this.accessKey = objPar.accessKey;        
	        }
	        if (rialto.lang.isNumber(objPar.tabIndex)){
	            this.tabIndex = objPar.tabIndex;
	        }  
	    }      
    
    //release object
	objPar=null;
	objParam=null;

    var oThis=this;

        
    // *******************************************
	// GENERATION OF DOM ELEMENTS
	// *******************************************/
        
    //FIRST DIV
    this.divExt.id = this.id + "_DivGen";
    this.divExt.style.position = this.position;
    this.divExt.style.left = this.left + "px";
    this.divExt.style.top = this.top + "px";
    this.divExt.style.width = this.width;
    this.divExt.style.height = 20;
    this.divExt.className = "champs-div";
    //Activate the onselect event with input
    this.divExt.onselectstart=function(){return true};
    var strInner="";            
	if (this.datatype == "T") {
	    strInner="<TEXTAREA  name='"+this.name+"'/>";
    }
    else{
	    strInner="<input type='"+this.inputType+"' name='"+this.name+"'/>";	    
	}                  
	this.divExt.innerHTML=strInner;
    if (parent) {this.placeIn(parent);};
}    
    
    
rialto.widget.Text.prototype = new rialto.widget.AbstractComponent;


//to change style attribute
rialto.widget.Text.prototype.adaptToContext=function() {
    //HTML INPUT
    var oThis=this;
    
    this.champs=this.divExt.childNodes[0];
    
    if (this.datatype == "T") {
	    //this.champs = document.createElement("TEXTAREA");
	    this.champs.style.border="1px solid rgb(120,172,255)";    
	    this.champs.rows=this.rows;
    }
    else{
	    //this.champs = document.createElement("INPUT");    
	    //this.champs.type = this.inputType;  
	    //this.champs.type= this.inputType;  
	    this.champs.style.border = "1px inset rgb(212,208,200)";	    
	}      
	
 
    //this.champs.name = this.name;
    this.champs.tabIndex = this.tabIndex;    
    this.champs.maxlength = this.nbchar;
    this.champs.accessKey = this.accessKey;

	//Activate the onselect event with input
    //this.champs.onselectstart=function(){return true};
	
	
    this.champs.style.width='100%';
    //init value
    if (this.initValue) {        
        this.setValue(this.initValue);        
    }  
    //BUG MOZILLA
	this.champs.setAttribute("autocomplete","off");
    
    //DIFFERENT SORT OF INPUT
    if (this.datatype == "N") {
        this.champs.className = "champs-num";
    }
    else if (this.datatype == "A") {
        this.champs.className = "champs-alpha";
    }
    else if (this.datatype == "I") {
        this.autoUp=false;
        this.champs.className = "champs-dossier";
        this.divExt.style.width=80;
        this.champs.style.width=80;
        this.champs.size = 10;
        this.champs.maxlength = 10;
    }    
    else if (this.datatype == "D") {
        this.autoUp=false;
        this.champs.className = "champs-date";
        this.divExt.style.width=115;
        this.champs.style.width=80;
        this.champs.size = 10;
        this.champs.maxlength = 10;
        //help image      
        this.hlpimg =new rialto.widget.Image('pinkHelpButton',80,-2,this.divExt,"Afficher le calendrier",'redHelpButton',{position:'absolute'});                  
        this.hlpimg.onclick = function(e){
            if (!e) e=window.event
            oThis.openCalendar(e);
        }
    }
    else if (this.datatype == "H") {
        this.autoUp=false;
        this.champs.className = "champs-alpha";
        this.divExt.style.width=40;
        this.champs.style.width=40;
        this.champs.size = 5;
        this.champs.maxlength = 5;       
    }
    
    //ENABLE STATE
    if (this.disable) {        
        this.setEnable(false);
    }
    
        
    //REQUIRED STATE
    if (this.isRequired) {
        champsAs = document.createElement("DIV");
        champsAs.innerHTML="*";
        champsAs.style.position="absolute";
        champsAs.style.top=0;
        champsAs.style.left=-7;
        champsAs.style.color="red";
        this.divExt.appendChild(champsAs);        
    }
                
    //EVENT FONCTION (only if not hidden input)
    if (this.datatype != "Hi"){   
	    this.champs.onkeypress = function (e){
	        if (!e) var e = window.event;
	        //check the key                
	        return oThis.checkKeyPress(e);        
	    };    
	    
	    this.champs.onmousedown = function (e){
	        if (!e) var e = window.event;
	        stopEvent(e);        
	    };  
	    
	    this.champs.onfocus = function (e){
	        if (!e) var e = window.event;        
	        oThis.afterOnFocus();
	    };
	    
	    this.champs.onblur = function (e){        
	        if (!e) var e = window.event;
	        oThis.afterOnBlur();
	    };
	    
	    
	    this.champs.onclick = function () {
	        this.focus();
	        return true;
	    }        
	    
	    this.champs.ondbleclick = function () {
	        this.select();
	        return true;
	    } 
	}    
} 



//to change style attribute
rialto.widget.Text.prototype.release=function() {           
	this.divExt.onselectstar=null;
	this.champs.onkeypress = null;        
    this.champs.onfocus = null;    
    this.champs.onblur = null;
    this.champs.onclick = null;
    this.champs.ondbleclic=null;
    if (this.datatype == "D") {
	    this.hlpimg.onclick=null;
    	this.hlpimg.remove();
    	if(this.calendar){  
	    	this.calendar.onclick=null;
		    this.calendar.remove();
		}
    }
}


//to change style attribute
rialto.widget.Text.prototype.setStyle=function(obStyle) {           
    for (prop in obStyle){                
        try {            
            this.champs.style[prop]=obStyle[prop];
        }
        catch (erreur) {}        
    }                                    
}

//TO OPEN A CALENDAR
rialto.widget.Text.prototype.openCalendar=function(e) {         
    var othis=this;        
    if(!this.calendar){  
	    this.calendar=new rialto.widget.Calendar({popUpMode:true});    
    	this.calendar.onclick=function(date){
        	othis.setValue(date);
	        othis.setFocus();        
    	}    
    }
    //date saisie
    var top=compOffsetTop(this.divExt)+27;
    var left=compOffsetLeft(this.divExt)-90; 
   
    //si on deborde on met 0
    if (left<0){left=0;}
    this.calendar.displayCalendar(top,left);
}


//TO CHECK THE KEY PRESS ACCORDING TO DATATYPE....
rialto.widget.Text.prototype.checkKeyPress=function(evt) {
    //boolean to cancel the keypress
    var boolCancel=false;
	//boolean to change the key press
    boolReplaceKey=false;
    
    //length -->kneed to be see again (probleme when text is sel an try to type a new key)	
	/*
	if ((this.champs.value.length + 1) > this.champs.maxlength) {         	        
		if(window.event){return false;}
		else{
			var oldSelectionStart = this.champs.selectionStart;
		    var oldSelectionEnd = this.champs.selectionEnd;
		    if(oldSelectionEnd-oldSelectionStart==0){ 
		        return false;
		    }
		}
	}
    */
	//keycode according to the browser
	var keyCode = evt.keyCode ? evt.keyCode :
                            evt.charCode ? evt.charCode :
                                            evt.which ? evt.which : void 0;
    
    var key;
    if (keyCode) {
    	key = String.fromCharCode(keyCode);
    }    
    /**********ESCAPE KEY*******/
	//Alt key
    if(evt.altKey){return true;}
    if(evt.ctrlKey){return true;}
    //to have tab(9),backspace(8),delete(46),left arrow(37) and right arrow(39)in MOZILLA (problem with type date because same code that . or %)
	
    if(keyCode==9 || (keyCode==37) || (keyCode==39) ||(keyCode==46) || keyCode==8){
    	return true
    };
    
    
    //If enter (and not textarea)
    if (keyCode == 13 && this.datatype != "T") {              
        //make blur               
        this.champs.blur();       
        return  this.blurOK
    }
    
    //this.champs.value.maxlength = (this.nbchar);    		

    // TYPE DOSSIER IGR
    if (this.datatype == 'I') {
        boolCancel= "0123456789-".indexOf(key) == -1        
    }
    
    //IF UPPERCASE
    if (this.autoUp == true){
       var newKey = key.toUpperCase();       
       if(newKey != key) {
           boolReplaceKey=true;
           key=newKey;       
       }
    }
    
    //IF NUMBER
    if (this.datatype == 'N') {       
        boolCancel= "0123456789".indexOf(key) == -1
    }
    
    //IF DATE
    if (this.datatype == 'D') {
        boolCancel= "0123456789/".indexOf(key) == -1     
    }
    
    //IF HOUR----->kneed to be see again
    if (this.datatype == 'H') {                 
        if("0123456789:".indexOf(key) == -1){
            boolCancel=true
        }
        else{
            // if : is not the third character
            if(key==":" && this.champs.value.length!=2) {
                boolCancel= true;
            }            
        }       
    }
   
    //WHAT TO DO ACCORDING TO PREVIOUS TEST
    //WITH INTERNET EXPLORER
    if (keyCode && window.event && !window.opera) {
    //TO CANCEL
    if (boolCancel) {
      return false;
    }
    else if (boolReplaceKey) {
      //TO REPLACE WITH NEWVAL
      window.event.keyCode = key.charCodeAt();
      if (window.event.preventDefault) {
        window.event.preventDefault();
      }
      return true;
    }
    else {
      return true;
    }
  }
  //WITH MOZILLA
  else if (typeof this.champs.setSelectionRange != 'undefined') {
    //TO CANCEL
    if (boolCancel) {
      if (evt.preventDefault) {

        evt.preventDefault();
      }
      return false;
    }
    //TO REPLACE WITH NEWVAL
    else if (boolReplaceKey) {
      //Cancel anywhere
      if (evt.preventDefault) {
	  evt.preventDefault();
      }
      //new key
      var oldSelectionStart = this.champs.selectionStart;
      var oldSelectionEnd = this.champs.selectionEnd;
            
      this.champs.value = 
        this.champs.value.substring(0, oldSelectionStart) +
        key +
        this.champs.value.substring(oldSelectionEnd);
      
      //put the cursor at the end
      this.champs.setSelectionRange(oldSelectionStart + key.length,
                                    oldSelectionStart + key.length);
      return false;
    }
    else {
      return true;
    } 
  }
  //OTHER CASE
  else if (boolCancel) {
    if (evt.preventDefault) {
      evt.preventDefault();
    }
    return false;
  }
  else {
    return true;
  }
}

//TO DO ONFOCUS
rialto.widget.Text.prototype.afterOnFocus=function () { 
    //Select the input content
    //for ie to enable the select
    document.onselectstart=function(){return true};
    this.champs.select();
    //set the boolean before change
    this.blurOK=true;
    this.wchanged = false;
    //this.wvalue = this.champs.value;    
    //call applicative code
    this.onfocus();    
}

//To display a message
//if boolSetFoc reset the field and give him the focus after the close of the alert
rialto.widget.Text.prototype.displayMessage=function (str,boolSetFoc) {    
    var oThis=this;
    info = new rialto.widget.Alert(str);
    //On donne le focus au chalos suite au message
    if(boolSetFoc){
        info.onclose=function(){                        
        	oThis.setValue("");
	        oThis.champs.focus();
        }
        info=null;
    }
}
           

//FONCTION DE PERTE DE FOCUS
rialto.widget.Text.prototype.afterOnBlur=function () {  		
	if(this.champs.value != ""){	    
	    //remove white space
	    this.champs.value = rialto.string.trim(this.champs.value);

		//MAKE ALL THE CONTROL ACCORDING TO THE DATATYPE				
	    if (this.datatype == 'N' && this.champs.value != "") {
	        //check number               
	        if (!rialto.lang.isNumber(this.champs.value)) {	            
	            this.displayMessage("MUST BE A NUMBER",true);
	            //valeur de retour            
	            this.blurOK= false;            
	        }
	    }
	    	    if (this.datatype == 'D' && this.champs.value != "") {
	        //check date               
	        if (!this.checkDate()) {	            
	            this.displayMessage("Date is not correct, format must be: DD/MM/YYYY",true);
	            //valeur de retour            
	            this.blurOK= false;            
	        }
	    }
	    if (this.datatype == 'H' && this.champs.value != "") {
	        //check hour  
	        if (!this.checkHour()) {
	            this.displayMessage("Hour is not correct, format must be: HH:MM",true);
	            //valeur de retour            
	            this.blurOK= false;            
	        }
	    }
	    //SPECIFIC KIND OF FIELD FOR HOSPITAL FOLDER
	    if (this.datatype == 'I' && this.champs.value != "") {
	        // Formatage du champs de type n? de dossier IGR
	        var wDoss = this.champs.value;
	        var wPos = wDoss.indexOf("-");
	        var wPre = "";
	        var wSuf = "";
	        if (wPos == -1) {
	            if (wDoss.length <= 5) {
	              wPre = new Date().getYear().toString();
	              wSuf = wDoss;
	              window.status = "1: " + wPre + ":" + wSuf;
	            }
	            else {
	                wPre = wDoss.substring(0,4);
	                wSuf = wDoss.substring(4,wDoss.length);                
	            }
	        }
	        else {
	            wPre = wDoss.substring(0,wPos);
	            wSuf = wDoss.substring(wPos+1,wDoss.length);
	        }
	        // Padding du pr?fixe
	        if (wPre == "") {wPre = new Date().getYear().toString();}
	        if (wPre.length == 1) {wPre = ("200"+wPre);}
	        if (wPre.length == 2 && wPre < "30") {wPre = ("20"+wPre);}
	        if (wPre.length == 2 && wPre >= "30") {wPre = ("19"+wPre);}
	        if (wPre.length == 3 && wPre < "030") {wPre = ("2"+wPre);}
	        if (wPre.length == 3 && wPre >= "030") {wPre = ("1"+wPre);}
	        // Padding du suffixe
	        if (wSuf.length < 5) {
	            var wPad = "";
	            for (var wI=wSuf.length;wI<=4;wI++) {
	                    wPad=(wPad+"0");
	            }
	            wSuf=(wPad+wSuf);            
	        }
	        if (wPre.length != 4 || wSuf.length != 5) {
	            this.displayMessage("Num?ro de dossier invalide, format utilisable: AA-NNNNN",true);
	           //valeur de retour
	            this.blurOK= false;            
	        }
	        else {
	            this.champs.value= (wPre + "-" + wSuf);
	        }
	    }
	    
	
	    //desactivate the selection
	    document.onselectstart=new Function ("return false");    
	    if(this.datatype!='P'){this.champs.title=this.champs.value;}
		
		//has change	    
        this.wchanged =(this.wvalue != this.champs.value)
		this.wvalue=this.champs.value;
	    //applicative code
	    if (this.wchanged && this.blurOK){
	        this.blurOK=this.onblur();    
	    }
      	this.removeAsRequired();
	 }
	 else{
	    this.blurOK=this.onblur();
		//if required
	    if(this.isRequired){
	        this.showAsRequired();
	        this.blurOK=false;
	    }
	 }
}

rialto.widget.Text.prototype.onblur=function () {    
//The code must be redefine after the instanciation of the component. By default this method does nothing. 
//must return a boolean indicating if we validate the value
    return true;
}

//return a boolean indicating if the valus has change since the last focus
rialto.widget.Text.prototype.hasChanged=function () {
    return this.wchanged;
}

//COHERENCE DE L'HEURE SAISIE
rialto.widget.Text.prototype.checkHour=function(){

	strHour = this.champs.value;
    //remove the : from the hour
    strHour=rialto.string.replace(strHour,":","");
    
    switch (strHour.length) {			
			case 1:
			    //Only hour
				h=parseInt(strHour);
				m=0;				
	   	        break;
		    case 2:
			    //Only hour
				if (parseInt(strHour.substring(0,1))==0){
					h=parseInt(strHour.substring(1,2));
				}
				else{
					h=parseInt(strHour);
				}
				m=0;				
	   	        break;			        
			case 4:    
				// hour and minute
				if (parseInt(strHour.substring(0,1))==0){
					h=parseInt(strHour.substring(1,2));
				}
				else{
					h=parseInt(strHour.substring(0,2));
				}				
    			m=parseInt(strHour.substring(2,4));
				break;          		        
			default:
		    	//not ok
		    	return false
			    break;    	   		                    	           	   		        
		}			    
    //new string value
    strHour=h<10?"0"+h:h;
    strHour+=":"+(m<10?"0"+m:m);
       
    //CHECK IF HOUR AND MINUTE OK
    if(h<=24 && m<=60 ){
        this.champs.value=strHour;
        return true;
    }
    else{return false;}
}


rialto.widget.Text.prototype.checkDate=function(){

    var oDate = new Date();
    strDate = this.champs.value;
    var curMonth=oDate.getMonth()+1;
    curMonth=(curMonth<10)? '0'+curMonth:curMonth
    var curYear=oDate.getFullYear();
        
    //remove the / from the date    
    strDate=rialto.string.replace(strDate,"/","");
    switch (strDate.length) {
				case 1:
					// it is the day add the month and the year
		   	      	strDate="0"+strDate+"/"+curMonth+"/"+curYear;
			        break;
				case 2:
					// it is the day add the month and the year
					strDate=strDate+"/"+curMonth+"/"+curYear;
				    break;
				case 3:
				    // it is the day+the month add the year
					strDate=strDate.slice(0,2)+"/0"+strDate.charAt(2)+"/"+curYear;
		   	        break;            
				case 4:    
					// it is the day+the month add the year
					strDate=strDate.slice(0,2)+"/"+strDate.slice(2,4)+"/"+curYear;
					break;          		        
		        case 6:  				   	
		            // it is the day+the month and the last number of the year
		            strDate=strDate.slice(0,2)+"/"+strDate.slice(2,4)+"/20"+strDate.slice(4,6);
    		        break;
		        case 8:  				   	
		            // day,month and year            
                    strDate=strDate.slice(0,2)+"/"+strDate.slice(2,4)+"/"+strDate.slice(4,8);
	   		        break;
				default:
			    	//Not ok
			    	return false
				    break;    	   		                    	           	   		        
			}			
        
    // Check the date
    if(rialto.date.isDate(strDate)){
        this.setValue(strDate);
        return true;
    }
    else{return false;}
}


//give the focus to the field
rialto.widget.Text.prototype.setFocus=function(){    
    this.champs.focus();
}

//return the value of the field
rialto.widget.Text.prototype.getValue=function(){
    return this.champs.value;
}

//set the value of the field
rialto.widget.Text.prototype.setValue=function(text){
    this.champs.value=text;
    this.wvalue=text;
    //if nor password add the tooltip
    if(this.datatype!='P'){this.champs.title=text;}      
}

//******those 2 METHODS ARE DEPRECATED...USE SETENABLE
//to enable
rialto.widget.Text.prototype.active=function() {
	rialto.deprecated('Text','active','setEnable(true)');
    this.setEnable(true);
}
//to desable
rialto.widget.Text.prototype.inactive=function() {
	rialto.deprecated('Text','inactive','setEnable(false)');
    this.setEnable(false); 
}
//******

//this method will allow to enable or disable the input according to the parameter
rialto.widget.Text.prototype.setEnable=function(enable){
	if(enable){
		this.champs.style.color="black";
	    this.champs.disabled=false;
	    this.champs.style.backgroundColor = "white";
	    this.champs.style.border = "1px inset rgb(212,208,200)";    
	    if (this.datatype == "D") {this.hlpimg.setEnable(true);}
	}
	else{
		this.champs.disabled=true;
    	this.champs.style.color="gray";    
    	this.champs.style.backgroundColor = "#DDDDDD";
    	if (this.datatype == "D") {this.hlpimg.setEnable(false);}
	}
	this.enable=enable;
}

//to show that the field haven't been fill
rialto.widget.Text.prototype.showAsRequired=function(){    
    this.champs.style.border = "1px solid red";    
}

//to remove the indication that the field haven't been fill
rialto.widget.Text.prototype.removeAsRequired=function(){    
    this.champs.style.border = "1px inset rgb(212,208,200)";    
}



